import React from "react";
import {
  Button,
  Icon,
  Modal,
  Upload,
  Tooltip,
  Spin,
  message,
  Row,
  Popover,
  Col,
  Radio,
  notification,
  Popconfirm,
} from "antd";
import { connect } from "react-redux";
import HanWang from "components/han-wang";
import ScannerButton from "components/scanner-button/scanner-button";
import Canon from "components/canon-scan/canon-scan";
import { messages, queryCurrencyPrecision } from "share/common";
import ResizeTable from "components/resize-table";
import CreateInvoice from "containers/my-account/create-invoice";
import Invoice from "containers/my-account/invoice";
import SlideFrame from "components/slide-frame";
import baseService from "share/base.service";
import financeAuditService from "containers/financial-management/finance-audit/finance-audit.service";
import invoiceBagApproveService from "containers/financial-management/invoice-bag-approve/invoice-bag-approve.service";
import CounterModal from "containers/financial-management/new-finance-audit/components/counter-modal";
import InvoiceManualCheck from "containers/financial-management/new-finance-audit/components/invoice-manual-check";
import Condition from "components/condition";
import expenseService from "containers/my-account/expense.service";

const { If, Else } = Condition;
const RadioGroup = Radio.Group;
class AuditApplicationInvoices extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      filter: {
        checkTab: "all", //全部、未匹配、已核对，未核对
        includeLabel: true,
        label: [],
      },
      columns: [
        {
          dataIndex: "index",
          title: messages("financial-management.key403") /*序号*/,
          render: (text, record, index) => index + 1,
          width: 50,
        },
        {
          dataIndex: "type",
          title: messages("common.invoice.type") /*发票类型*/,
          width: 200,
          render: (text) => (
            <div className="bad-table-cell" style={{ width: 184 }}>
              <Tooltip title={text} placement="topLeft">
                {text}
              </Tooltip>
            </div>
          ),
          sorter: (a, b) => (a.type > b.type ? 1 : -1),
        },
        {
          dataIndex: "billingCode",
          title: messages("financial-management.key611") /*发票代码*/,
          width: 200,
          render: (text) => (
            <Tooltip title={text} placement="topLeft">
              {text || "-"}
            </Tooltip>
          ),
          sorter: (a, b) => (a.billingCode > b.billingCode ? 1 : -1),
        },
        {
          dataIndex: "billingNo",
          title: messages("financial-management.key612") /*发票号码*/,
          width: 100,
          render: (text) => (
            <div className="bad-table-cell" style={{ width: 84 }}>
              <Tooltip title={text} placement="topLeft">
                {text || "-"}
              </Tooltip>
            </div>
          ),
          sorter: (a, b) => (a.billingNo > b.billingNo ? 1 : -1),
        },
        {
          dataIndex: "billingTime",
          title: messages("financial-management.key613") /*开票日期*/,
          width: 100,
          render: (billingTime) =>
            billingTime
              ? new Date(billingTime * 1000).format("yyyy-MM-dd")
              : "-",
          sorter: (a, b) => a.billingTime - b.billingTime,
        },
        {
          dataIndex: "vatInvoiceCurrencyCode",
          title: messages("financial-management.key405") /*币种*/,
          width: 50,
          render: (text) => (
            <Tooltip title={text} placement="topLeft">
              {text}
            </Tooltip>
          ),
        },
        {
          dataIndex: "feeWithoutTax",
          title: messages("financial-management.key614") /*金额合计*/,
          width: 100,
          render: (feeWithoutTax, record) =>
            feeWithoutTax === null ? (
              <span className="money-cell">-</span>
            ) : (
              this.filterMoney(
                feeWithoutTax / 100,
                queryCurrencyPrecision(record.vatInvoiceCurrencyCode)
              )
            ),
        },
        {
          dataIndex: "taxRate",
          title: messages("financial-management.key747") /*税率*/,
          width: 100,
          render: (taxRate, record) => (taxRate === null ? record.invoiceGoods[0].taxRate ? record.invoiceGoods[0].taxRate + '%' : "-" : `${taxRate * 100}%`),
        },
        {
          dataIndex: "tax",
          title: messages("common.tax") /*税额*/,
          width: 100,
          render: (tax, record) =>
            tax === null ? (
              <span className="money-cell">-</span>
            ) : (
              this.filterMoney(
                (tax || 0) / 100,
                queryCurrencyPrecision(record.vatInvoiceCurrencyCode)
              )
            ),
        },
        {
          dataIndex: "fee",
          title: messages("financial-management.key616") /*价税合计*/,
          width: 100,
          render: (fee, record) =>
            this.filterMoney(
              fee / 100,
              queryCurrencyPrecision(record.vatInvoiceCurrencyCode)
            ),
          sorter: (a, b) => a.fee - b.fee,
        },
        {
          dataIndex: "invoiceGoods",
          title: messages("financial-management.key748") /*发票商品服务名称*/,
          width: 200,
          render: (invoiceGoods) => {
            let text =
              invoiceGoods.map((goods) => goods.goodsName).join("、") || "-";
            return (
              <div className="bad-table-cell" style={{ width: 184 }}>
                <Tooltip
                  title={text}
                  overlayStyle={{ width: 200, whiteSpace: "pre-wrap" }}
                  placement="topLeft"
                >
                  {text}
                </Tooltip>
              </div>
            );
          },
        },
        {
          dataIndex: "slicingAttachment",
          title: messages("common.attachments") /*附件*/,
          width: 50,
          className: "attachment-col",
          render: (slicingAttachment) =>
            slicingAttachment ? (
              <Tooltip
                placement="leftTop"
                overlayClassName="audit-application-invoices-tooltip"
                getPopupContainer={(triggerNode) => triggerNode.parentNode}
                autoAdjustOverflow={false}
                title={
                  <img
                    src={slicingAttachment.fileURL}
                    style={{ width: 400 }}
                    alt=""
                  />
                }
              >
                <a>1</a>
              </Tooltip>
            ) : (
              "-"
            ),
        },
        {
          dataIndex: "id",
          title: messages("financial-management.key254") /*操作*/,
          width: 100,
          render: this.renderOperationColumns,
        },
      ],
      // 核票中
      checking: false,
      loading: false,
      applicantFp: {},
      currencyList: [],
      showFinanceInvoiceFlag: false,
      showExpenseInvoiceFlag: false,
      nowFinanceInvoice: null,
      nowExpenseInvoice: null,
      invoiceList: {
        financeReceipts: [],
        freeReceipt: [],
        withReceipt: [],
        withReceiptStatistics: null,
        financeReceiptStatistics: null,
        freeReceiptStatistics: null,
      },
      expandedList: [],
      unexpandedList: [],
      loadingInvoice: null,
      scanning: false,
      disabled: false,
      showOCRFlag: false,
      cacheScanResult: { success: 0, error: 0 },
      cacheReceiptList: [], // 缓存发票信息
      cacheClaimInfo: [], // 缓存单据信息 识别完统一处理
      claimSourceData: [], // 表单显示单据信息
      dataSource: {
        tip1: {
          errorMsg:
            "已识别的发票信息还未保存，请勿刷新或关闭此页面，避免数据丢失。",
          normal: "若误操作导致发票信息已清空，请重新扫描发票或拍发票；",
        },
        tip2:
          "若本单据还有其他发票未扫描，您可停留在此页面继续操作扫描发票或拍发票，也可进入单据详情后再操作；",
        tip3: "",
      },
    };
  }

  mapFinanceInvoice = (invoice) => {
    invoice.isFinance = true;
    if (!invoice.type)
      invoice.type = messages("financial-management.key775") /*无法识别*/;
    return invoice;
  };

  getInvoiceLabel = () => {
    const {
      filter,
      invoiceList: { financeReceipts, withReceipt, freeReceipt },
    } = this.state;
    const invoiceLabels = [];
    const filterInvoice = (receiptsList) =>
      receiptsList
        .filter((item) => {
          if (filter.checkTab === "all") return true;
          return item.checkTag === filter.checkTab;
        })
        .forEach((invoice) => {
          if (invoice.receiptLabels) {
            invoice.receiptLabels.forEach((label) => {
              if (!invoiceLabels.find((l) => l.type === label.type))
                invoiceLabels.push({
                  name: label.name,
                  type: label.type,
                  level: label.level,
                });
            });
          }
        });
    filterInvoice(financeReceipts.concat(withReceipt, freeReceipt));
    this.setState({ invoiceLabels });
  };

  onChangeFilter = (key, value) => {
    let { filter } = this.state;
    filter[key] = value;
    if (key === "checkTab") filter.label = [];
    this.setState({ filter }, () => this.getInvoiceLabel());
  };

  componentDidMount() {
    const { info, onRef, isAuditInApproveStatus } = this.props;
    if (onRef) {
      onRef(this);
    }
    this.getOCRisOpen();
    let applicantOID = info.applicantOID;
    this.setState({
      loading: true,
      disabled: info.status !== 1003 && !isAuditInApproveStatus,
    });
    Promise.all([
      baseService.getAllCurrencyByLanguage("zh_cn", applicantOID, true),
      baseService.getFpByUserOID(applicantOID),
      financeAuditService.getExpenseReportInvoices(info.expenseReportOID),
    ])
      .then((res) => {
        res[2].data.financeReceipts.forEach(this.mapFinanceInvoice);
        this.setState({
          loading: false,
          currencyList: res[0].data,
          applicantFp: res[1].data,
          invoiceList: res[2].data,
        });
      })
      .catch(() => {
        this.setState({ loading: false });
      });
  }

  renderOperationColumns = (id, record) => {
    const { loadingInvoice, disabled } = this.state;
    let isFinance = record.isFinance;
    let editOperation = (
      <a onClick={() => this.handleEditFinanceInvoice(id)}>
        {messages("financial-management.key500") /*编辑*/}
      </a>
    );
    let viewOperation = (
      <a onClick={() => this.handleViewExpenseInvoice(id)}>
        {messages("common.view") /*查看*/}
      </a>
    );
    if (id === loadingInvoice) return <Spin />;
    if (isFinance) {
      return disabled ? (
        viewOperation
      ) : (
        <span>
          <Popconfirm
            title={
              messages(
                "financial-management.key749"
              ) /*你确定要删除这张发票吗？*/
            }
            onConfirm={() => this.handleDeleteInvoice(id)}
          >
            <a>{messages("financial-management.key501") /*删除*/}</a>
          </Popconfirm>
          <span className="ant-divider" />
          {record.checkResult === "R_0000" || record.alipayOrWeChat
            ? viewOperation
            : editOperation}
        </span>
      );
    } else {
      return viewOperation;
    }
  };

  handleDeleteInvoice = (id) => {
    this.setState({ loading: true });
    financeAuditService
      .deleteFinanceInvoice(id)
      .then(() => {
        message.success(messages("common.operate.success") /*操作成功*/);
        this.refreshList();
      })
      .catch(() => {
        this.setState({ loading: false });
      });
  };

  handleEditFinanceInvoice = (id) => {
    const { loadingInvoice } = this.state;
    if (loadingInvoice) {
      message.error(messages("financial-management.key750") /*请等待*/);
      return;
    }
    this.setState({ loadingInvoice: id });
    financeAuditService
      .getInvoiceDetail(id)
      .then((res) => {
        this.setState(
          { nowFinanceInvoice: res.data },
          this.toState({ showFinanceInvoiceFlag: true, loadingInvoice: null })
        );
      })
      .catch(() => {
        this.setState({ loadingInvoice: null });
      });
  };

  handleViewExpenseInvoice = (id) => {
    const { loadingInvoice } = this.state;
    if (loadingInvoice) {
      message.error(messages("financial-management.key750") /*请等待*/);
      return;
    }
    this.setState({ loadingInvoice: id });
    financeAuditService
      .getInvoiceDetail(id)
      .then((res) => {
        this.setState(
          { nowExpenseInvoice: res.data },
          this.toState({ showExpenseInvoiceFlag: true, loadingInvoice: null })
        );
      })
      .catch(() => {
        this.setState({ loadingInvoice: null });
      });
  };

  handleCreateFinanceInvoice = () => {
    this.setState(
      { nowFinanceInvoice: {} },
      this.toState({ showFinanceInvoiceFlag: true })
    );
  };

  afterCreateFinanceInvoice = () => {
    this.setState(
      { showFinanceInvoiceFlag: false, nowFinanceInvoice: null },
      this.refreshList
    );
  };

  refreshList = () => {
    this.setState({ loading: true });
    const { baseInfo } = this.props;
    financeAuditService
      .getExpenseReportInvoices(baseInfo.expenseReportOID)
      .then((res) => {
        res.data.financeReceipts.forEach(this.mapFinanceInvoice);
        this.setState({ invoiceList: res.data, loading: false });
      });
  };

  handleClickInfo = () => {
    Modal.info({
      title: messages("financial-management.key414") /*说明*/,
      content: (
        <div>
          <p>
            {
              messages("financial-management.key787")
              /*1.【扫描发票】：请购买汉王 Q3200AF型号高拍仪，用于批量扫描发票（建议和自动审核功能一起使用）。*/
            }
          </p>
          <p>
            {
              messages("financial-management.key788")
              /*2.财务扫描发票：此处显示【扫描发票】、【录入发票】来源的发票；可编辑、删除发票。*/
            }
          </p>
          <p>
            {
              messages("financial-management.key789")
              /*3.免贴票发票：此处显示员工录入的，有【免贴票】标签的发票；可查看发票。*/
            }
          </p>
        </div>
      ),
    });
  };

  getExpandedRender = (record) => {
    if (record.receiptLabels) {
      return record.receiptLabels
        .filter((item) => item.type !== "INSP_SUCCEEDED")
        .map((item) => item.name)
        .join(",");
    } else {
      return null;
    }
  };

  renderClass = (record) => {
    let result = "";
    result +=
      record.receiptLabels &&
      record.receiptLabels.filter((item) => item.type !== "INSP_SUCCEEDED")
        .length > 0
        ? ""
        : "row-expand-display-none";

    if (record.checkTag === "NOT_MATCHED") result += " error-table-line";
    if (record.checkTag === "TO_BE_CHECKED") result += " warn-table-line";
    return result;
  };

  getAmount = (data, rate = 100) => {
    if (!data) return `${this.props.company.baseCurrency} 0.00`;
    if (data.length === 0) {
      return "0.00";
    } else {
      let map = {};
      data.map((item) => {
        Object.keys(item).map((key) => {
          map[key] = item[key];
        });
      });
      return Object.keys(map)
        .map(
          (c) =>
            `${c} ${this.filterMoney(
              map[c] / rate,
              queryCurrencyPrecision(c),
              true
            )}`
        )
        .join(" , ");
    }
  };

  sortFinanceInvoice = (a, b) => a.billingTime - b.billingTime;

  onExpand = (expanded, record) => {
    const unexpandedList = this.state.unexpandedList.filter(
      (item) => item !== record.id
    );
    if (!expanded) {
      unexpandedList.push(record.id);
    }
    this.setState({ unexpandedList });
  };

  getExpandedRowKeys = (list, name) => {
    const keys = [];
    list.forEach((item) => {
      if (!this.state.unexpandedList.includes(item.id)) {
        keys.push(item.id);
      }
    });
    return keys;
  };

  handleUpload = (file) => {
    new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = (error) => reject(error);
    }).then((base64) => {
      // return
      this.handleScan_OLD(base64);
    });
    return false;
  };

  handleScan_OLD = (base64) => {
    const key = `open${Date.now()}`;
    const { info } = this.props;
    this.setState({ scanning: true });
    notification.open({
      key,
      message: messages("financial-management.key782") /*识别中...*/,
      icon: <Icon type="loading" />,
      duration: null,
    });
    financeAuditService
      .scanBase64(base64, info.id)
      .then((res) => {
        if (res.data.success) {
          let method = "info";
          switch (res.data.code) {
            case 130113:
              method = "success";
              break;
            case 130114:
              method = "warning";
              break;
            case 130115:
              method = "error";
              break;
          }
          this.setState({ scanning: false });
          this.refreshList();
          notification.close(key);
          notification[method]({
            message: res.data.message,
            duration: 4,
          });
        } else {
          this.setState({ scanning: false });
          notification.close(key);
          message.error(
            messages("financial-management.key801") /*扫描失败，请稍后重试*/
          );
        }
      })
      .catch(() => {
        this.setState({ scanning: true });
        notification.close(key);
      });
  };

  handleScan = (params, scanCounter) => {
    const key = `open${Date.now()}`;
    const { info } = this.props;
    const { cacheScanResult } = this.state;
    return new Promise((resolve, reject) => {
      financeAuditService
        .scanBase64(params.imageData, info.id)
        .then((res) => {
          if (res.data.success) {
            let method = "info";
            switch (res.data.code) {
              case 130113:
                method = "success";
                break;
              case 130114:
                method = "warning";
                break;
              case 130115:
                method = "error";
                break;
            }
            cacheScanResult.success += res.data.rows.length;
            resolve();
            // this.setState({ scanning: false });
            // notification.close(key);
            // notification[method]({
            //   message: res.data.message,
            //   duration: 4,
            // });
          } else {
            cacheScanResult.error++;

            reject(
              new Error(
                messages("financial-management.key801") /*扫描失败，请稍后重试*/
              )
            );
            // this.setState({ scanning: false });
            // notification.close(key);
            // message.error(
            //   messages("financial-management.key801") /*扫描失败，请稍后重试*/
            // );
          }
        })
        .catch((error) => {
          cacheScanResult.error++;
          reject(error);
        })
        .finally(() => {
          this.setState({ cacheScanResult });
          if (scanCounter) {
            scanCounter.num++;
            scanCounter.error = cacheScanResult.error;
            scanCounter.success = cacheScanResult.success;
            this.ScannerButton.refreshScanProps({ scanCounter });
          }
        });
    });
  };

  scanEndHandle = () => {
    console.log("发票扫描结束");
    const { cacheScanResult } = this.state;
    const key = "scanEndHandle";
    this.setState({ cacheScanResult: { success: 0, error: 0 } });
    this.refreshList();
    notification.open({
      key,
      message: `扫描结束`,
      description: `识别成功${cacheScanResult.success}张发票，失败${cacheScanResult.error}张发票。`,
      duration: 3,
    });
  };

  // 汉王的识别loading外部实现 卷票机的识别loading内部实现
  handleScan_PUBLIC = (params, scanCounter) => {
    return new Promise((resolve, reject) => {
      const result = {
        error: 0,
        success: 0,
      };
      financeAuditService
        .scanAuditReceipt(params)
        .then((res) => {
          // 识别先缓存信息 结束统一处理
          const expenseReportList =
            this.safeGet(res.data, "expenseReportList") || [];
          const receiptList = this.safeGet(res.data, "receiptList") || [];
          result.success += receiptList.length;
          this.setState(
            {
              cacheClaimInfo: [
                ...this.state.cacheClaimInfo,
                ...expenseReportList,
              ],
              cacheReceiptList: [
                ...this.state.cacheReceiptList,
                ...receiptList,
              ],
            },
            () => {
              resolve();
            }
          );
        })
        .catch((error) => {
          reject(error);
        })
        .finally(() => {
          if (scanCounter) {
            scanCounter.num++;
            scanCounter.error += result.error;
            scanCounter.success += result.success;
            this.ScannerButton.refreshScanProps({ scanCounter });
          }
        });
    });
  };

  scanEndHandle_PUBLIC = () => {
    console.log("发票扫描结束");

    let dataSource = JSON.parse(JSON.stringify(this.state.dataSource));
    dataSource.tip3 = `当前已识别${this.state.cacheReceiptList.length}张发票，基于发票类型、发票代码、发票号码匹配，以下单据可找到对应的发票，请选择一个单据进入详情，则所有已识别的发票信息将默认带入此单据；若找不到对应单据，您可扫描更多此单据的发票来匹配或直接进入单据详情-发票模式，操作扫描发票/拍发票。`;
    this.setState(
      {
        dataSource,
        scanStatus: true,
        claimLoading: true,
      },
      () => {
        let claimSourceData = JSON.parse(
          JSON.stringify(this.state.claimSourceData)
        );
        this.state.cacheClaimInfo.forEach((item) => {
          let currentItem = claimSourceData.find(
            (claim) => claim.expenseReportOID === item.expenseReportOID
          );
          if (currentItem) {
            currentItem.matchedReceiptCount += item.matchedReceiptCount;
            return !1;
          }
          if (!currentItem && item.expenseReportOID) {
            claimSourceData.push(item);
            return !1;
          }
        });
        claimSourceData.sort(
          (a, b) => b.matchedReceiptCount - a.matchedReceiptCount
        );
        this.setState(
          {
            claimSourceData,
            cacheClaimInfo: [],
            claimLoading: false,
          },
          () => {
            let { rowSelection } = this.state;
            // 默认选中第一行
            if (claimSourceData[0] && rowSelection.selectedRowKeys.length < 1) {
              this.onSelectItem(claimSourceData[0]);
            }
          }
        );
      }
    );
  };

  onSelectItem = (record) => {
    let { rowSelection } = this.state;
    rowSelection.selectedRowKeys = [record.expenseReportOID];
    this.setState({
      selectedData: record,
      rowSelection,
    });
  };

  getInvoiceList = (refresh) => {
    const { baseInfo } = this.props;
    this.setState({ loading: true });
    financeAuditService
      .getExpenseReportInvoices(baseInfo.expenseReportOID)
      .then((res) => {
        res.data.financeReceipts.forEach(this.mapFinanceInvoice);
        this.setState({ invoiceList: res.data, loading: false });
      });
  };

  getInfo = () => {
    this.getInvoiceList();
    // this.props.onRowSelectionChange([]);
    this.setState({
      selectedFinanceReceipts: [],
      selectedWithReceipt: [],
      selectedFreeReceipt: [],
    });
  };
  onEventTrack = ({
    errorInfo = false,
    notOCRFlag = false,
    disabled = false,
    responseTime = 0,
  }) => {
    const { tenantInfo, enableScan } = this.props;
    let errorType = "无";
    if (notOCRFlag) {
      errorType = "未开通OCR";
    }
    if (disabled) {
      errorType = "未检测到驱动";
    }
    if (errorInfo) {
      errorType = errorInfo;
    }
    console.log({
      category: "财务扫发票",
      action: "租户名称+卷票机类型+报错类型+调用识别接口时间",
      label: [
        tenantInfo.tenantName,
        enableScan,
        errorType,
        responseTime + "s",
      ].join(" "),
    });
  };
  renderAutoCheckResult = (notMatchedNum, toBeCheckedNum) => {
    let interval,
      counter = 3;
    const modal = Modal.confirm({
      content: (
        <CounterModal
          type="AUTO_CHECK"
          params={{ notMatchedNum, toBeCheckedNum }}
        />
      ),
      iconType: "exclamation-circle",
      onOk: () => {
        clearInterval(interval);
        this.setState({ showManualCheck: true });
      },
      onCancel: () => {
        clearInterval(interval);
        this.getInfo();
      },
    });
    interval = setInterval(() => {
      counter--;
      if (!counter) {
        clearInterval(interval);
        modal.destroy();
        this.setState({ showManualCheck: true });
      }
    }, 1000);
  };

  /**
   * 是否开通发票查验和OCR
   * @returns {Promise<*>}
   */
  getOCRisOpen = () => {
    const {
      loginUser: { userOID },
    } = this.props;
    expenseService.getTitleList(userOID).then((res) => {
      this.setState({
        showOCRFlag: res.data.showOCRFlag,
      });
    });
  };

  checkInvoice = () => {
    this.setState({ checking: true });
    const { invoiceBagId, baseInfo } = this.props;
    (invoiceBagId
      ? invoiceBagApproveService.checkInvoices(invoiceBagId)
      : financeAuditService.expenseCheckInvoice(baseInfo.expenseReportOID)
    )
      .then((res) => {
        const { notMatchedNum, toBeCheckedNum } = res.data || {};
        this.setState({ notMatchedNum }, () => {
          if (notMatchedNum === 0 && toBeCheckedNum === 0) {
            message.success(
              messages("expense-15.key72") /*全部发票已核对正确*/
            );
            this.getInfo();
          } else {
            //进入人工核票
            this.renderAutoCheckResult(notMatchedNum, toBeCheckedNum);
          }
        });
      })
      .finally(() => {
        this.setState({ checking: false });
      });
  };

  filterCheckTag = (record) => {
    const { filter } = this.state;
    let recordIncludeLabel =
      record.receiptLabels &&
      record.receiptLabels.find(
        (label) => filter.label.indexOf(label.type) > -1
      );
    let labels =
      filter.label.length === 0 ||
      (filter.includeLabel ? recordIncludeLabel : !recordIncludeLabel);
    return filter.checkTab === "all"
      ? labels
      : !!(record.checkTag === filter.checkTab && labels);
  };

  render() {
    const { info, baseInfo, company, invoiceBagId } = this.props;
    const {
      showManualCheck,
      checking,
      columns,
      showFinanceInvoiceFlag,
      nowFinanceInvoice,
      applicantFp,
      currencyList,
      filter,
      disabled,
      showExpenseInvoiceFlag,
      nowExpenseInvoice,
      notMatchedNum,
      invoiceList,
      loading,
      scanning,
      showOCRFlag,
    } = this.state;

    const { withReceipt, financeReceipts, manualCheckType } = invoiceList;

    return (
      <div className="audit-application-invoices">
        {!disabled && (
          <div className="invoice-list-head">
            <Row type="flex" justify="space-between">
              <Col>
                <Radio.Group
                  onChange={(e) =>
                    this.onChangeFilter("checkTab", e.target.value)
                  }
                  value={filter.checkTab}
                >
                  <Radio.Button value="all">全部</Radio.Button>
                  <Radio.Button
                    value="NOT_MATCHED"
                    className="error-table-line"
                  >
                    未匹配
                  </Radio.Button>
                  <Radio.Button
                    value="TO_BE_CHECKED"
                    className="warn-table-line"
                  >
                    待匹配
                  </Radio.Button>
                  <Radio.Button value="CHECKED">已核对</Radio.Button>
                </Radio.Group>
              </Col>
              <Col className="button-row">
                <span>
                  {false && (
                    <HanWang
                      buttonProps={{ type: "primary", loading: scanning }}
                      onCapture={this.handleScan}
                    >
                      {messages("financial-management.key783") /*扫描发票*/}
                    </HanWang>
                  )}
                  <ScannerButton
                    text="扫描发票"
                    buttonProps={{ type: showOCRFlag ? "primary" : "default" }}
                    showOCRFlag={showOCRFlag}
                    onScan={this.handleScan}
                    onStopScan={this.scanEndHandle}
                    onRef={(ref) => (this.ScannerButton = ref)}
                  />
                  <Icon
                    type="info-circle"
                    onClick={this.handleClickInfo}
                    className="scan-info-icon"
                  />
                </span>
                {["mcddev2020.huilianyi.com", "localhost"].includes(
                  location.hostname
                ) && (
                  <Upload
                    style={{ marginRight: 16 }}
                    showUploadList={false}
                    beforeUpload={this.handleUpload}
                  >
                    <Button>上传发票</Button>
                  </Upload>
                )}
                <Button
                  className="button"
                  onClick={this.handleCreateFinanceInvoice}
                >
                  {messages("financial-management.key784") /*录入发票*/}
                </Button>

                <Button
                  className="button"
                  onClick={this.checkInvoice}
                  loading={checking}
                >
                  {messages("expense-15.key76") /*自动核票*/}
                </Button>

                <Condition>
                  <If value={manualCheckType !== 1000}>
                    <Popover
                      placement="topRight"
                      content={
                        manualCheckType === 1001
                          ? "全部发票已核对正确"
                          : manualCheckType === 1002
                          ? "请先操作自动核票"
                          : "无发票可核对"
                      }
                    >
                      <Button disabled>人工核票</Button>
                    </Popover>
                  </If>
                  <Else>
                    <Button
                      onClick={() => this.setState({ showManualCheck: true })}
                    >
                      人工核票
                    </Button>
                  </Else>
                </Condition>
              </Col>
            </Row>
          </div>
        )}
        <div className="table-count">
          <b style={{ marginRight: 10 }}>财务扫描</b>
          {messages("financial-management.key752") /*发票数量*/}
          <b className="number">{invoiceList.financeReceipts.length}</b>
          <span className="ant-divider" />{" "}
          {messages("financial-management.key753") /*总计*/}
          <b className="number">
            {this.getAmount(invoiceList.financeReceiptStatistics, 1)}
          </b>
        </div>
        <ResizeTable
          columns={columns}
          // dataSource={invoiceList.financeReceipts.sort(this.sortFinanceInvoice)}
          dataSource={invoiceList.financeReceipts.filter(this.filterCheckTag)}
          pagination={false}
          rowKey="id"
          size="middle"
          loading={loading}
          expandedRowRender={this.getExpandedRender}
          rowClassName={this.renderClass}
          onExpand={this.onExpand}
          expandedRowKeys={this.getExpandedRowKeys(
            invoiceList.financeReceipts,
            "financeReceipts"
          )}
        />
        {nowFinanceInvoice && (
          <SlideFrame
            content={CreateInvoice}
            show={showFinanceInvoiceFlag}
            hasFooter={false}
            params={{
              userOID: info.applicantOID,
              receipt: nowFinanceInvoice,
              invoiceUserFp: applicantFp,
              currencyList,
              createType: 2,
              receiptOperateScene: 3,
              onCreate: this.afterCreateFinanceInvoice,
              receiptList: [],
              onBack: this.toState({ showFinanceInvoiceFlag: false }),
              expenseReportId: info.id,
              currency:
                nowFinanceInvoice.vatInvoiceCurrencyCode ||
                company.baseCurrency,
            }}
            onClose={this.toState({ showFinanceInvoiceFlag: false })}
            afterClose={this.toState({
              showFinanceInvoiceFlag: false,
              nowFinanceInvoice: null,
            })}
            title={messages("financial-management.key784") /*录入发票*/}
          />
        )}

        <div className="table-count" style={{ marginTop: 30 }}>
          <b style={{ marginRight: 10 }}>员工录入（需贴票）</b>
          发票数量
          <b className="number">{invoiceList.withReceipt.length}</b>
          <span className="ant-divider" />
          总计
          <b className="number">
            {this.getAmount(invoiceList.withReceiptStatistics)}
          </b>
        </div>
        <div style={{ position: "relative" }}>
          <ResizeTable
            // showUtils
            // tableName={`invoice-bag-approve.withReceipt`}
            columns={columns}
            // onResize={(newColumns) => this.onChangeColumns(newColumns, "WithReceipt")}
            // onSort={(newColumns) => this.onChangeColumns(newColumns, "WithReceipt")}
            // bordered
            rowKey="id"
            expandedRowRender={this.getExpandedRender}
            loading={loading}
            pagination={false}
            rowClassName={this.renderClass}
            scroll={{ x: true }}
            dataSource={invoiceList.withReceipt.filter(this.filterCheckTag)}
            size="middle"
            // expandIconAsCell={false}
            onExpand={this.onExpand}
            expandedRowKeys={this.getExpandedRowKeys(invoiceList.withReceipt)}
            // rowSelection={isWaitForAudit ? rowSelection : null}
            // onRef={(ref) => (this.withReceiptRed = ref)}
          />
        </div>

        <div className="table-count" style={{ marginTop: 30 }}>
          <b style={{ marginRight: 10 }}>员工录入（免贴票）</b>
          {messages("financial-management.key752") /*发票数量*/}
          <b className="number">{invoiceList.freeReceipt.length}</b>
          <span className="ant-divider" />{" "}
          {messages("financial-management.key753") /*总计*/}
          <b className="number">
            {this.getAmount(invoiceList.freeReceiptStatistics)}
          </b>
        </div>
        <ResizeTable
          columns={columns}
          // dataSource={invoiceList.freeReceipt.sort(this.sortFinanceInvoice)}
          dataSource={invoiceList.freeReceipt.filter(this.filterCheckTag)}
          pagination={false}
          rowKey="id"
          size="middle"
          loading={loading}
          expandedRowRender={this.getExpandedRender}
          rowClassName={this.renderClass}
          onExpand={this.onExpand}
          expandedRowKeys={this.getExpandedRowKeys(invoiceList.freeReceipt)}
        />
        {showManualCheck && (
          <InvoiceManualCheck
            visible
            entityType={invoiceBagId ? 5001 : 1002}
            entityID={baseInfo.id}
            entityOID={
              invoiceBagId
                ? baseInfo.expenseReportBagCode
                : baseInfo.expenseReportOID
            }
            userOID={invoiceBagId ? baseInfo.userOID : baseInfo.userOID}
            hasNotMatchReceipt={
              notMatchedNum > 0 ||
              financeReceipts
                .concat(withReceipt)
                .some((item) => item.checkTag === "NOT_MATCHED")
            }
            onCancel={() =>
              this.setState(
                { showManualCheck: false, notMatchedNum: 0 },
                this.getInfo
              )
            }
          />
        )}
        {nowExpenseInvoice && (
          <SlideFrame
            content={Invoice}
            show={showExpenseInvoiceFlag}
            hasFooter={false}
            afterClose={this.toState({
              showExpenseInvoiceFlag: false,
              nowExpenseInvoice: null,
            })}
            params={{
              invoiceList: [nowExpenseInvoice],
              disabledEdit: true,
              onBack: this.toState({ showExpenseInvoiceFlag: false }),
            }}
            onClose={this.toState({ showExpenseInvoiceFlag: false })}
            title={messages("financial-management.key756") /*查看发票*/}
          />
        )}
      </div>
    );
  }
}

AuditApplicationInvoices.contextTypes = {
  router: React.PropTypes.object,
};

AuditApplicationInvoices.PropTypes = {
  info: React.PropTypes.object,
  invoiceEnabled: React.PropTypes.bool,
  onRef: React.PropTypes.func, //全部查验后需要刷新列表
};

AuditApplicationInvoices.defaultProps = {
  info: {},
};

function mapStateToProps(state) {
  return {
    loginUser: state.login.loginUser,
    company: state.login.company,
  };
}

export default connect(mapStateToProps)(AuditApplicationInvoices);
